package com.yunsc.order.sevice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.order.dao.YunscOrderAddressDao;
import com.yunsc.order.entity.YunscOrderAddressEntity;
import com.yunsc.order.sevice.YunscOrderAddressService;
import com.yunsc.store.dao.YunscRegionDao;
import com.yunsc.store.entity.YunscUserAddressEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;


@Service("yunscOrderAddressService")
public class YunscOrderAddressServiceImpl extends ServiceImpl<YunscOrderAddressDao, YunscOrderAddressEntity> implements YunscOrderAddressService {

    @Resource
    private YunscRegionDao regionDAO;

    @Override
    public YunscOrderAddressEntity queryAddressByOrderId(Integer orderId) {
        YunscOrderAddressEntity address = this.getOne(new LambdaQueryWrapper<YunscOrderAddressEntity>()
                .eq(YunscOrderAddressEntity::getOrderId, orderId));
        if (address == null){
            return null;
        }
        Map<String, Object> map = regionDAO.getAddressByOrderId(address.getRegionId());
        address.setRegion(map);
        return address;
    }

    @Override
    @Transactional
    public void saveOrderAddressDB(YunscUserAddressEntity address, Integer userId, Integer orderId, Integer storeId) {
        YunscOrderAddressEntity orderAddress = new YunscOrderAddressEntity();
        if (address == null) {
            throw new YunscException("创建订单异常，地址不存在");
        }
        BeanUtils.copyProperties(address, orderAddress);
        orderAddress.setUserId(userId);
        orderAddress.setStoreId(storeId);
        orderAddress.setOrderId(orderId);
        // 订单地址保存
        boolean orderAddressSave = this.save(orderAddress);
        if (!orderAddressSave) {
            throw new YunscException("创建订单地址异常");
        }
    }
}